import { useEffect, useState } from 'react'
import fetchAxios, { useFetch } from '@/plugins/axios'
import { NotifyFetch, NotifyModel, transNoticeType } from './translate'
import { confirmModal } from '../Modal'
import { quitLogin } from '@/utils/common'
import { useNavigate } from 'react-router-dom'
import { SystemInfoProps } from '@/utils/interface'
import { CompanyInfoProps } from '@/utils/interface'
export const useNotices = () => {
	//hasNew 有新消息
	const [hasNew, setHasNew] = useState<number>(0)
	//noticeList 消息数据
	const [noticeList, setNoticeList] = useState<NotifyModel[]>([])
	const [noAlert, setNoAlert] = useState<NotifyModel[]>([])
	const [noRead, setNoRead] = useState<NotifyModel[]>([])
	const navigate = useNavigate()
	// //获取通知信息
	const [{ loading, response }, ListFetch] = useFetch<NotifyFetch>({
		url: '/web/messages',
		method: 'GET',
	})
	useEffect(() => {
		if (!loading) {
			if (response?.success) {
				const { list = [] } = response
				const notifys = list || []
				if (notifys) {
					let newList = transNoticeType(notifys)
					// console.log(transformSmcData(newList))
					// setNoticeList(newList)
					// smc消息归类
					// setNoticeList(transformSmcData(newList))
					setNoticeList(newList)
					// alertState 是否弹框 alertRead 是否读取
					setNoRead(newList.filter((item) => item.readState === 0))
					// 有新消息
					setHasNew(newList.filter((item) => item.readState === 0).length)
					// 未弹框的数据
					setNoAlert(newList.filter((item) => item.alertState === 0))
				}
			}
		}
	}, [response, loading])

	useEffect(() => {
		let interval = 5 * 60
		const id = setInterval(() => {
			ListFetch()
		}, interval * 1000)

		return () => clearInterval(id)
	}, [ListFetch])
	// transformSmcData  根据title分类
	interface infoType {
		[key: string]: Pick<NotifyModel, 'title' | 'data' | 'moid'>
	}

	const transformSmcData = (arr: NotifyModel[]) => {
		console.log(arr)
		var map: infoType = {},
			smcData = []
		for (let i = 0; i < arr.length; i++) {
			let ai = arr[i]
			if (Object.keys(map).indexOf(ai['title']) < 0) {
				smcData.push({
					title: ai['title'],
					type: ai['type'],
					data: [ai],
					moid: ai['moid'] + ',',
				})
				map[ai['title']] = ai
			} else {
				for (let j = 0; j < smcData.length; j++) {
					let dj = smcData[j]
					if (dj.title === ai['title']) {
						dj.data.push(ai)
						dj.moid += ai['moid'] + ','
						break
					}
				}
			}
		}
		return smcData
	}
	// 展开全读  未读字体加粗  未读moids
	const setStateReady = () => {
		let moids = ''
		for (let index = 0; index < noRead.length; index++) {
			moids += noRead[index]['moid'] + ','
		}
		fetchAxios({
			url: `/web/messages/states/read`,
			method: 'PUT',
			data: { moids: moids?.split(',') },
		}).then((res) => {
			if (res.success) {
				// 未读为0
				setHasNew(0)
			}
		})
	}
	// 标记已提醒
	const hadAlert = (ids?: string) => {
		fetchAxios({
			url: `/web/messages/states/alert`,
			method: 'PUT',
			data: { moids: ids?.split(',') },
		}).then((res) => {
			if (res.success) {
				// ListFetch()
			}
		})
	}
	// 删除消息列表  未读moids
	const clearNotice = () => {
		// let moids = ''
		// for (let index = 0; index < noticeList.length; index++) {
		// 	moids += noticeList[index]['moid'] + ','
		// }
		fetchAxios({
			url: `/web/messages/states/all?source=sac&type=SAC_ALARM`,
			method: 'DELETE',
		}).then((res) => {
			if (res.success) {
				ListFetch()
			}
		})
	}
	// 清除
	const hadDelete = (ids?: string) => {
		fetchAxios({
			url: `/web/messages/states`,
			method: 'DELETE',
			data: { moids: ids?.split(',') },
		}).then((res) => {
			if (res.success) {
				// 删除noticeList 数据中的一项
				const filter = noticeList.filter((item) => item.moid !== ids, [])
				setNoticeList(filter)
			}
		})
	}
	/**退出系统 */
	const exitSystem = () => {
		confirmModal({
			title: '提示',
			msg: '确定要退出吗？',
			onOk: () => {
				quitLogin()
				// window.location.href = `/meeting/logout`
			},
		})
	}
	/**返回首页 */
	const backToHome = () => {
		navigate(`/home`)
	}

	return {
		hasNew,
		noAlert,
		noRead,
		noticeList,
		setStateReady,
		hadAlert,
		clearNotice,
		hadDelete,
		exitSystem,
		ListFetch,
		backToHome,
	}
}
/**
 * 公司信息，用于头部不同品牌的信息展示
 * @returns companyInfo AboutBrand
 */
export const useCompanyInfo = (): {
	/**根据接口brand品牌，决定的公司皮肤信息 */
	companyInfo: CompanyInfoProps
} => {
	return {
		companyInfo: window.g_brand_company_info,
	}
}
